<template>
  <div class="wang-editor">
    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        :style="`height: ${minHeight}px; overflow-y: hidden;`"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>
    
    <!-- 隐藏的上传组件 -->
    <div style="display: none;">
      <image-upload ref="imageUploadRef" :limit="1" v-model="tempImage" />
    </div>
  </div>
</template>

<script setup>
import { ref, shallowRef, onBeforeUnmount, watch, getCurrentInstance, nextTick } from 'vue'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getToken } from '@/utils/auth'
import request from '@/utils/request'

// 定义props
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  minHeight: {
    type: Number,
    default: 500
  }
})

// 定义emit
const emit = defineEmits(['update:modelValue', 'change'])

// 获取全局配置和方法
const { proxy } = getCurrentInstance()

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 图片上传组件实例
const imageUploadRef = ref(null)
// 临时存储上传的图片
const tempImage = ref('')

// 内容 HTML
const valueHtml = ref(props.modelValue)

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  if (newValue !== valueHtml.value) {
    valueHtml.value = newValue
  }
}, { immediate: true })

// 监听内容变化
watch(() => valueHtml.value, (newValue) => {
  emit('update:modelValue', newValue)
  emit('change', newValue)
})

// 监听临时图片变化
watch(() => tempImage.value, (newValue) => {
  if (newValue && editorRef.value) {
    // 插入图片到编辑器
    editorRef.value.insertNode({
      type: 'image',
      attrs: {
        src: newValue,
        alt: '上传图片',
        style: 'max-width: 100%'
      }
    })
    // 清空临时图片，以便下次上传
    nextTick(() => {
      tempImage.value = ''
    })
  }
})

// 工具栏配置
const toolbarConfig = {
  excludeKeys: []  // 移除 uploadImage，允许使用图片上传功能
}

// 编辑器配置
const editorConfig = {
  placeholder: '请输入内容...',
  autoFocus: false,
  MENU_CONF: {
    uploadImage: {
      // 自定义上传
      customUpload(file, insertFn) {
        const formData = new FormData()
        formData.append('file', file)
        
        request({
          url: '/common/upload',
          method: 'POST',
          data: formData,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(res => {
          if (res.code === 200) {
            insertFn(res.url, file.name, res.url)
            proxy.$modal.msgSuccess('图片上传成功')
          } else {
            proxy.$modal.msgError(res.msg || '图片上传失败')
          }
        }).catch(error => {
          console.error('上传错误:', error)
          proxy.$modal.msgError('图片上传失败：' + (error.msg || '未知错误'))
        })
      }
    }
  }
}

// 编辑器模式
const mode = 'default' // 'default' 或 'simple'

// 组件销毁时，也销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 编辑器创建完成时的回调
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例
  editor.setHtml(valueHtml.value) // 设置初始内容
  
  // 添加自定义上传图片按钮
  const toolbar = editor.getToolbar()
  toolbar.insertBefore({
    key: 'customUploadImage',
    factory() {
      const $button = document.createElement('button')
      $button.textContent = '上传图片'
      $button.className = 'w-e-toolbar-item-button'
      $button.addEventListener('click', () => {
        // 调用项目中已有的图片上传组件
        if (imageUploadRef.value) {
          imageUploadRef.value.openDialog()
        }
      })
      return {
        $elem: $button
      }
    }
  }, 'insertImage') // 放在insertImage按钮前面
}
</script>

<style scoped>
.wang-editor {
  width: 100%;
}

:deep(.w-e-toolbar-item-button) {
  padding: 4px 10px;
  margin: 0 5px;
  cursor: pointer;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
}

:deep(.w-e-toolbar-item-button:hover) {
  background-color: #f5f7fa;
}
</style> 